import 'dart:async';

import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/http/bean/wroks/search_bean.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/bean/ywx_limit.dart';
import 'package:app/src/http/sign.dart';
import 'package:app/src/http/url.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import '../../manager/ywx_manager.dart';
import '../bean/worksdo/material_requisition_bean.dart';
import '../bean/wroks/dispatchingaudit_bean.dart';

///物料请购
class MaterialModel {
  ///获取审核列表数据 fixme （物料请购）
  ///ReviewType 审核类型
  ///PageNo 页码,从1开始。(物料请购是从1开始的，其他审核列表，是从0开始的)
  ///PageSize 每页显示条目数量
  ///searchInfo 搜索条件
  static Future<AppHttpResult<List<MaterialInfo>, MaterialInfo>>
      getWorkOvertimeApprovallist(BuildContext context, bool isEnableLoad,
          {String? reviewType,
          String? PageNo,
          String? PageSize = "15",
          SearchInfo? searchInfo}) async {
    Completer completer =
        new Completer<AppHttpResult<List<MaterialInfo>, MaterialInfo>>();
    var url = Url.baseurl() + Url.AjaxPurchase; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    //var url = "http://masapp.zuvowf.com/" + Url.contractdogetlist;//测试服务器访问受限制，数据返回为空。
    var token = AppDataConfig.getToken();
    var subData = SubData();
    subData.commondata = CommonData();
    subData.PageNo = PageNo;
    subData.PageSize = PageSize!;
    subData.InsertStartDatetime =
        searchInfo?.InsertStartDatetime ?? ""; //开始时间;物料请购这里不能传null
    subData.InsertEndDatetime = searchInfo?.InsertEndDatetime ?? ""; //结束时间
    //subData.businessdata = searchInfo?.getContractCopyInfo();//搜索条件
    SearchMaterialInfo searchMaterialInfo =
        SearchMaterialInfo.fromSerch(searchInfo);
    var mReviewType = reviewType;
    if (ReviewType.MaterialRequisition_Generated == reviewType) {
      //已生成
      mReviewType = ReviewType.MaterialRequisition_Generated;
    } else if (ReviewType.MaterialRequisition_OriginalRequisition ==
        reviewType) {
      //原片请购
      mReviewType = ReviewType.MaterialRequisition_NotGenerated;
      searchMaterialInfo?.MaterialType = PurDemand.MT01;
    } else if (ReviewType.MaterialRequisition_AccessoriesRequisition ==
        reviewType) {
      //辅料请购
      mReviewType = ReviewType.MaterialRequisition_NotGenerated;
      searchMaterialInfo?.MaterialType = PurDemand.MT02;
    } else if (ReviewType.MaterialRequisition_HardwareRequisition ==
        reviewType) {
      //五金请购
      mReviewType = ReviewType.MaterialRequisition_NotGenerated;
      searchMaterialInfo?.MaterialType = PurDemand.MT03;
    }
    subData.ReviewType = mReviewType;
    subData.businessdata = searchMaterialInfo; //fixme 搜索条件
    var queryParameters = Map<String, dynamic>();
    queryParameters['data'] = subData.jsonEncodeToJson();
    // PrintUtils.printlnLong('搜索数据：${ subData.jsonEncodeToJson()}');
    // print('搜索数据：${ subData.jsonEncodeToJson()}');
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<List<MaterialInfo>, MaterialInfo>>(
              AppHttpResult()
                ..Data = <MaterialInfo>[]
                ..t2 = MaterialInfo())
          ?.then((result) {
        if (!StringUtils.isEmpty(searchMaterialInfo?.MaterialType)) {
          result?.Data?.forEach((element) {
            if (element.isEmptyFactory()) {
              //防止工厂为空
              element.FactoryName = searchMaterialInfo?.FactoryName;
              element.FactoryId = searchMaterialInfo?.FactoryId;
            }
            var data = element;
            element.PurDemandList?.forEach((element) {
              if (StringUtils.isEmpty(element?.MaterialType)) {
                ///fixme 防止物料类型为空。
                element?.MaterialType = searchMaterialInfo?.MaterialType;
              }
              element.FactoryName = data.FactoryName;
              element.FactoryId = data.FactoryId;
            });
          });
        }
        completer.complete(result);
      });
    return completer.future
        as Future<AppHttpResult<List<MaterialInfo>, MaterialInfo>>;
  }

  ///请购单审核撤回
  static Future<AppHttpResult<String, String>> withdraw(
      BuildContext context, bool isEnableLoad, String? wfId,
      {String? PageNo, String? PageSize = "15", SearchInfo? searchInfo}) async {
    Completer completer = new Completer<AppHttpResult<String, String>>();
    var url = Url.baseurl() + Url.AjaxPurchase; //fixme 目前接口用的是审核类的接口，后面需要重新对接。
    //var url = "http://masapp.zuvowf.com/" + Url.contractdogetlist;//测试服务器访问受限制，数据返回为空。
    var token = AppDataConfig.getToken();
    var subData = SubData();
    subData.commondata = CommonData();
    subData.PageNo = PageNo;
    subData.PageSize = PageSize!;
    subData.InsertStartDatetime =
        searchInfo?.InsertStartDatetime ?? ""; //开始时间;物料请购这里不能传null
    subData.InsertEndDatetime = searchInfo?.InsertEndDatetime ?? ""; //结束时间
    //subData.businessdata = searchInfo?.getContractCopyInfo();//搜索条件
    SearchMaterialInfo searchMaterialInfo =
        SearchMaterialInfo.fromSerch(searchInfo);
    var mReviewType = "withdrawWF";
    subData.ReviewType = mReviewType;
    subData.wfId = wfId;
    subData.businessdata = searchMaterialInfo; //fixme 搜索条件
    var queryParameters = Map<String, dynamic>();
    queryParameters['data'] = subData.jsonEncodeToJson();
    // PrintUtils.printlnLong('搜索数据：${ subData.jsonEncodeToJson()}');
    // print('搜索数据：${ subData.jsonEncodeToJson()}');
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        completer.complete(null); //fixme 这里也返回一下；防止列表没有收到回调，一直处于刷新的状态；
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('数据返回:\n$result');
        if (StringUtils.isEmpty(result)) {
          completer.complete(null);
        }
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<String, String>>(AppHttpResult()
            ..Data = ""
            ..t2 = "")
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future as Future<AppHttpResult<String, String>>;
  }

  ///物料请购提交
  ///Status 状态(保存，提交)
  ///Intro 审核意见
  ///pics 图片地址（多张图片用|分隔）
  ///subData 审核提交数据
  static Future<AppHttpResult<String, String>> SavePurDemand(
      BuildContext context, bool isEnableLoad, String Status,
      {String? pics = null, SubData? subData = null}) async {
    Completer completer = new Completer<AppHttpResult<String, String>>();
    var url = Url.baseurl() + Url.AjaxPurchase;
    var token = AppDataConfig.getToken();
    if (subData == null) {
      subData = SubData();
    }
    subData.commondata = CommonData();
    // subData.ReviewType = AuditManager.item!.ReviewType!; //审核类型
    // subData.businessdata = AuditManager.ReviewTypeId; //审核类型ID
    // subData.YwxId = AuditManager.YwxId;
    // subData.YwxName = AuditManager.YwxName;
    // subData.Status = Status; //审核状态
    // subData.Intro = Intro; //审核意见
    subData.ReviewType = "SavePurDemand"; //物料请购保存
    subData.businessdata = SearchMaterialInfo();
    subData?.purDemand?.setSave(Status);
    if (StringUtils.isEmpty(subData?.purDemand?.CreaterIdOld) ||
        subData?.purDemand?.CreaterIdOld == "0") {
      ///当创建人的id为空时；把token赋值给CreaterId；如果不为空，就不赋值。
      subData?.purDemand?.CreaterId = AppDataConfig.getToken();
      subData?.purDemand?.Creater = subData?.purDemand?.CreaterId;
    }
    if (StringUtils.isEmpty(subData?.purDemand?.PurStartDate)) {
      ///"PurEndDate": "2023-02-01",
      ///PurStartDate 采购开始时间
      subData?.purDemand?.PurStartDate =
          DateTimeUtils.getDateTimeFormat(dateAndTime: false);
    }

    ///设置物料请求状态(提交，保存)
    if (pics != null) {
      subData.pics = pics; //图片地址（多张图片用|分隔）
    }
    subData?.purDemand?.setFiles(subData.getPics());
    //print("图片：${subData?.purDemand?.FilePatch}");
    var queryParameters = Map<String, dynamic>();
    queryParameters['data'] = subData.jsonEncodeToJson();
    // print('物料请购提交数据：${subData.jsonEncodeToJson()}');
    // return Future.value(null);
    //print("================================================token:$token");
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    var isEnableLog = AppDataConfig.isEnableLog;
    //isEnableLog=true;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        //print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        //print('物料请购提交返回:\n$result');
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = isEnableLog
      ..postASync<AppHttpResult<String, String>>(AppHttpResult()
            ..Data = ""
            ..t2 = "")
          ?.then((result) {
        completer.complete(result);
      });
    return completer.future as Future<AppHttpResult<String, String>>;
  }

  //物料请购；获取物料种类；品牌；创建人，项目名称
  static void getOtherWorkApply2(
      BuildContext context,
      PreSearchMaterialInfo data,
      bool isEnableLoad,
      ResponseCallbackWithT<
              AppHttpResult<List<OtherWorkApply>?, OtherWorkApply?>>
          callback) {
    var url = Url.baseurl() + Url.getOtherPurchaseDLL;
    var queryParameters = Map<String, dynamic>();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // queryParameters['data'] = subData.jsonEncodeToJson();
    var dataJson = data.jsonEncodeToJson();
    // print("提交数据:$dataJson");
    queryParameters['data'] = dataJson;
    var token = AppDataConfig.getToken();
    var sign = getSign(queryParameters);
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      ..onStart(() {
        // print("请求url:$url");
        // print('请求参数:\t${queryParameters['data']}');
      })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('搜索返回结果:\n$result');
      })
      ..onFinish(() {
        // print('结束');
      })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..addFormData('sign', sign)
      ..isAllowedRepeat = true //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..isCache(true)
      ..postASync<AppHttpResult<List<OtherWorkApply>?, OtherWorkApply?>>(
              AppHttpResult()
                ..Data = <OtherWorkApply>[]
                ..t2 = OtherWorkApply())
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }

  //物料请购；获取物料库存
  static void getStockNum(
      BuildContext context,
      PurDemand data,
      bool isEnableLoad,
      ResponseCallbackWithT<AppHttpResult<String?, String?>> callback) {
    var url = Url.baseurl() + Url.getMaterialStockNum; //fixme 接口需要对接哦
    var queryParameters = Map<String, dynamic>();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // queryParameters['data'] = subData.jsonEncodeToJson();
    //data.MaterialCode = ""; //置空。防止异常。
    PurDemand? data2 = data.copy(); //fixme 重新复制一份数据。防止数据错乱。
    data2.MaterialCode = ""; //fixme 物料编码置空。
    data2.Thickness = ""; //fixme 厚度置空。
    data2?.Lengths = ""; //fixme 长置空
    data2?.Numbers = ""; //fixme 数量置空。
    queryParameters['data'] = data2.jsonEncodeToJson();
    data2 = null; //数据清除
    var token = AppDataConfig.getToken();
    var sign = getSign(queryParameters);
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      ..onStart(() {
        // print("请求url:$url");
        // print('请求参数:\t${queryParameters['data']}');
      })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        //{"StockNum":0,"MsgCode":"100","MsgDetail":"数据获取成功"}
        //{"StockNum":0,"MsgCode":"100","MsgDetail":"数据获取成功"}
        // print('库存数量返回结果:\n$result');
      })
      ..onFinish(() {
        // print('结束');
      })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..addFormData('sign', sign)
      ..isAllowedRepeat = true //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      //..isCache(true)
      ..postASync<AppHttpResult<String?, String?>>(AppHttpResult()
            ..Data = ""
            ..t2 = "")
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }
}
